package com.docMan.quartz;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.TopDocs;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.docMan.bean.IndexFile;
import com.docMan.lucene.Indexer;
import com.docMan.lucene.Searcher;
import com.docMan.utils.ClassUtil;
import com.docMan.utils.FinalConfig;
import com.docMan.utils.ProjectUtils;
import com.docMan.utils.dbUtils;

public class IndexOaJob implements Job {
	 private Logger logger=Logger.getLogger(IndexOaJob.class);
	final static String sql1578 = "select RECID,SWBH,LWBH,TO_CHAR(INSHEETDATE,'yyyy-mm-dd'),LWDW,LWBT,INSHEETDATE,FIELD11583 from TZREC1578 where INSHEETDATE>=? and INSHEETDATE is not null ORDER BY INSHEETDATE ";
	final static String sql1830 = "select RECID,SWBH,LWBH,TO_CHAR(INSHEETDATE,'yyyy-mm-dd'),LWDW,LWBT,INSHEETDATE,FIELD11582 from TZREC1830 where INSHEETDATE>=? and INSHEETDATE is not null ORDER BY INSHEETDATE ";
	final static String sql1963 = "select RECID,SWBH,LWBH,TO_CHAR(INSHEETDATE,'yyyy-mm-dd'),LWDW,LWBT,INSHEETDATE,'否' from TZREC1963 where INSHEETDATE>=? and INSHEETDATE is not null ORDER BY INSHEETDATE ";
	/**
	 * OAtable最后的索引id的文件位置
	 */
	/*String path = IndexOaJob.class.getClassLoader().getResource("").toURI().getPath()
			+ "oaIndexId.txt";*/
	/**
	 * 多域搜索的map<字段名，字段值>
	 */
	Map<String, String> termParamMaps = new HashMap<String, String>();
	/**
	 * map<lineNum,String[表明名字，该表最后的索引id]>
	 */
	List<String[]> oaMaps = new ArrayList<String[]>();

	@SuppressWarnings("resource")
	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		logger.error("quart renwu "+ new Date(System.currentTimeMillis()).toString());
		termParamMaps.put("indexFrom", FinalConfig.INDEX_FORM_OA);
		try {
			dbUtils dbu = new dbUtils();
			/*
			 * File file = new File(path); System.out.println(file.isFile());
			 * System.out.println(file.exists()); if (file.isFile() &&
			 * file.exists()) {
			 */
			InputStream in = ClassUtil.getClassLoader().getResourceAsStream(
					"oaIndexId.txt");
			/*
			 * InputStreamReader reader = new InputStreamReader( new
			 * FileInputStream(file));
			 */
			InputStreamReader reader = new InputStreamReader(in);
			BufferedReader bufferedReader = new BufferedReader(reader);
			String oaLine = null;
			while ((oaLine = bufferedReader.readLine()) != null) {
				String[] job = oaLine.split("=");
				oaMaps.add(job);
			}
			// }
			Indexer indexer = Indexer.getInstance(FinalConfig.index_dir);
			Searcher searcher = new Searcher(FinalConfig.index_dir);
			for (int i = 0; i < oaMaps.size(); i++) {
				String[] oaTable = oaMaps.get(i);
				String tableName = oaTable[0];
				String lastIndexDate = oaTable[1];
				String sql = getSql(tableName);
				//检测过去15天的文件有没有被标注为重要文件的
				long date7=15*24*3600*1000;
				Date date7ago=new Date(System.currentTimeMillis()-date7);
				ResultSet rs = dbu.executeQueryRS(sql, date7ago);
				System.out.println("日期大于" + date7ago.toString() + "文件");
				String lastIndexDateS = null;
				int count=0;
				while (rs.next()&&count<30) {
					lastIndexDateS = rs.getDate(7).toString();
					termParamMaps.put("id", rs.getString(1));
					TopDocs hits = searcher.TermsQueryL(termParamMaps);
					if (hits.scoreDocs.length == 0) {
						IndexFile indexFile = new IndexFile();
						indexFile.setFileId(rs.getString(1));
						indexFile.setSWBH(rs.getString(2) == null ? "无" : rs
								.getString(2));
						indexFile.setLWBH(rs.getString(3) == null ? "无" : rs
								.getString(3));
						indexFile.setCreateTime(rs.getString(4));
						indexFile.setLWDW(rs.getString(5) == null ? "无" : rs
								.getString(5));
						indexFile.setFileName(rs.getString(6) == null ? "无"
								: rs.getString(6));
						indexFile.setLWBT(rs.getString(6) == null ? "无" : rs
								.getString(6));
						indexFile.setDate(rs.getDate(7));
						indexFile.setIndexFrom(FinalConfig.INDEX_FORM_OA);
						indexFile.setContent(indexFile.getFileName() + "-"
								+ indexFile.getSWBH() + "-"
								+ indexFile.getLWDW() + "-"
								+ indexFile.getLWBT() + "-"
								+ indexFile.getLWBH());
						indexFile.setSearchAble(FinalConfig.searchType_all);
						indexFile
								.setIsImportantFile(null == rs.getString(8) ? "否"
										: "是".equals(rs.getString(8)) ? "是": "否");
						indexer.indexOAFile(indexFile);
						logger.error("make index for the oadocId is "+indexFile.getFileId()+"-----"+rs.getDate(7).toString());
						System.out.println(tableName+"-"+rs.getDate(7).toString()+"--"+rs.getString(1));
						count++;
					}
				}
				if (lastIndexDateS !=null) {
					oaTable[1] = String.valueOf(lastIndexDateS);
					oaMaps.set(i, oaTable);
				} else {
					System.out.println("数据表：" + oaTable[0] + "已经已全部索引");
				}
				writeOaTableLastIndexId(oaMaps);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 将OA每个表的最后索引id更新到文件中
	 * 
	 * @param oaMaps
	 * @throws IOException
	 * @throws URISyntaxException 
	 */
	private void writeOaTableLastIndexId(List<String[]> oaMaps)
			throws IOException, URISyntaxException {
		BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(
				new File(IndexOaJob.class.getClassLoader().getResource("").toURI().getPath()
						+ "oaIndexId.txt")));
		for (int i = 0; i < oaMaps.size(); i++) {
			String oaTableIndexId = oaMaps.get(i)[0] + "=" + oaMaps.get(i)[1];
			bufferedWriter.write(oaTableIndexId);
			if (i <= oaMaps.size() - 1) {
				bufferedWriter.newLine();
			}
		}
		bufferedWriter.flush();
		bufferedWriter.close();
	}

	private String getSql(String tableName) {
		if (tableName.endsWith("1578"))
			return sql1578;
		if (tableName.endsWith("1830")) {
			return sql1830;
		} else {
			return sql1963;
		}
	}

}
